<?php
/**
 * Created by PhpStorm
 * User: 陈志洪
 * Date: 2020/1/21
 * Time: 21:53
 */

namespace app\api\controller;

use app\api\library\WeChat\Payment;
use app\api\model\Order as OrderModel;
use app\api\service\OrderService;
use app\api\service\PayService;
use app\api\service\TokenService;
use think\Db;
use think\Exception;
use think\Log;
use function fast\array_get;

class Pay extends Base
{
    // 微信支付回调
    public function response()
    {
        Log::info('开始支付回调处理：' . date('Y-m-d H:i:s'));

        return (new Payment())->app->handlePaidNotify(function ($message, $fail) {
            $order = OrderModel::get(['order_number' => $message['out_trade_no']]); // 获取订单数据
            if (!$order || $order['status'] != 0) { // 订单不存在或订单已支付
                Log::info('结束支付回调处理 ------ 订单不存在或订单已支付');
                return true;
            }
            if ($message['return_code'] == 'SUCCESS') {
                // 用户是否支付成功
                if (array_get($message, 'result_code') === 'SUCCESS') {
                    Db::startTrans();
                    try {
                        /**
                         * @Todo 1.支付成功后将订单状态改成待核销状态
                         * @Todo 2.生成核销二维码与核销编码
                         */
                        (new OrderService())->updateOrderStatus($order['id']); //修改订单状态为已支付
                        (new OrderService())->updateCancelNumber($order['id'], $order['product_id']); //核销编码
                        $qr_number = (new OrderModel())->where('id', '=', $order['id'])->value('qr_number');
                        $data = [
                            'qr_number' => self::lock_url($qr_number,'password')//核销编号并加密
                        ];
                        (new OrderService())->updateQrCode(json_encode($data), $order['id']); //核销二维码


                        Db::commit();
                    } catch (Exception $e) {
                        Db::rollback();
                        Log::info('[error] 支付回调失败 ' . date('Y-m-d H:i:s') . '，错误原因：' . $e->getMessage());
                    }

                    // 用户支付失败
                } elseif (array_get($message, 'result_code') == 'FAIL') {
                    // 支付失败业务代码
                    // ...
                    // 支付失败业务代码
                }
            } else {
                Log::info('通知失败');
                return $fail('通信失败，请稍后再通知我');
            }

            Log::info('结束支付回调处理：' . date('Y-m-d H:i:s'));
            return true;
        });
    }
}
